package com.irun.ibuffet.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.irun.ibuffet.model.Response;

/***
 * @author huangsm
 * @date 2013-2-19
 * @email huangsanm@gmail.com
 * @desc http请求封装
 */
public class HttpUtils {

	public static final String ERROR = "http请求错误";
	public static final int METHOD_GET = 0;
	public static final int METHOD_POST = 1;
	
	/**
	 * 设置httpclient参数
	 * @return
	 */
	private static DefaultHttpClient getDefaultHttpClient() {
		DefaultHttpClient mHttpClient = new DefaultHttpClient();
		HttpParams mHttpParams = mHttpClient.getParams();
		mHttpParams.setParameter("http.protocol.content-charset", HTTP.UTF_8);
		mHttpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Constants.CONNECTION_TIME_OUT);
		mHttpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, Constants.CONNECTION_TIME_OUT);
		return mHttpClient;
	}
	
	/**
	 * 请求结果
	 * @param url
	 * @param method
	 * @param params
	 * @return
	 */
	public static Response getRequestEntity(String url, int method, List<NameValuePair> params){
		Response result;
		switch (method) {
			case METHOD_GET:
				result = httpGet(url, params);
				break;
			case METHOD_POST:
				result = httpPost(url, params);
				break;
			default :
				result = new Response(Constants.REQUEST_FAILURE, -1, ERROR);
				break;
		}
		return result;
	}
	
	/**
	 * post请求
	 * @param url
	 * @param params
	 * @return 
	 */
	private static Response httpPost(String url, List<NameValuePair> params){
		int statusCode = -1;
		String error = "";
		try {
			DefaultHttpClient client = getDefaultHttpClient();
			HttpPost post = new HttpPost(url);
			//post.addHeader("Content-Type", "application/json; charset=utf-8");
			//设置参数
			if(params != null && !params.isEmpty())
				post.setEntity(new UrlEncodedFormEntity(params));
			
			HttpResponse response = client.execute(post);
			statusCode = response.getStatusLine().getStatusCode();
			if(statusCode == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity, HTTP.UTF_8);
				return new Response(result, statusCode, Constants.REQUEST_SUCCESS);
			}
		} catch (UnsupportedEncodingException e) {
			error = e.getMessage();
		} catch (ClientProtocolException e) {
			error = e.getMessage();
		} catch (IOException e) {
			error = e.getMessage();
		}
		return new Response(Constants.REQUEST_FAILURE, statusCode, error);
	}
	
	/**
	 * 处理get请求
	 * @param url
	 * @param params
	 * @return 
	 */
	private static Response httpGet(String url, List<NameValuePair> params){
		int statusCode = -1;
		String error = "";
		try {
			DefaultHttpClient client = getDefaultHttpClient();
			//get请求添加请求参数
			final String uri = addParams(url, params);
			HttpGet get = new HttpGet(uri);
			HttpResponse response = client.execute(get);
			statusCode = response.getStatusLine().getStatusCode();
			if(statusCode == HttpStatus.SC_OK){
				HttpEntity entity = response.getEntity();
				String result = EntityUtils.toString(entity, HTTP.UTF_8);
				return new Response(result, statusCode, Constants.REQUEST_SUCCESS);
			}
		} catch (ClientProtocolException e) {
			error = e.getMessage();
		} catch (IOException e) {
			error = e.getMessage();
		}
		return new Response(Constants.REQUEST_FAILURE, statusCode, error);
	}
	
	/**
	 * get请求设置url参数
	 * @param url
	 * @param params
	 * @return
	 */
	private static String addParams(String url, List<NameValuePair> params){
		if(params == null || params.isEmpty()){
			return url;
		}
		
		StringBuffer p = new StringBuffer(url);
		p.append(url.contains("?") ? "&" : "?");
		final int len = params.size();
		for (int i = 0; i < len; i++) {
			NameValuePair nvp = params.get(i);
			p.append(nvp.getName()).append("=").append(nvp.getValue()).append("&");
		}
		
		if(Constants.DEBUG)
			System.out.println("url:" + p.substring(0, p.length() - 1));
			
		return p.substring(0, p.length() - 1);
	}
}
